package com.ldzy.controller;

import com.ldzy.pojo.MyResponse;
import com.ldzy.pojo.ResultCode;
import com.ldzy.pojo.User;
import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Controller
public class MyController {

    @PostMapping("testParam")
    @ResponseBody
    public MyResponse testParam(@RequestBody @Validated User user){
        System.out.println(user);
        MyResponse<Object> myResponse = new MyResponse<>(ResultCode.SUCCESS);
        myResponse.setData(user);
        return myResponse;
    }

    @GetMapping("/testException")
    @ResponseBody
    public MyResponse testException(Integer age){
        //如果age为年龄，范围为0-120，如何判断前端传递过来的是否在这个范围内，不在抛出异常
        System.out.println(age);
        age=10/age;
        MyResponse<Object> myResponse = new MyResponse<>(ResultCode.SUCCESS);
        //这个控制器只用来测试异常处理，该控制器执行过程中，有可能会发生异常：没有传值，不是整数转换失败，传入为0
        myResponse.setData(age);
        return myResponse;

    }

    @GetMapping("logout")
    public String logout(HttpSession session){
        //退出登录，服务器删除session
        session.invalidate();
        return "login";
    }
    @GetMapping("toOrderInfoPage")
    public ModelAndView toOrderInfoPage(){//返回登录页面
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("orderinfo");
        return modelAndView;
    }
    @GetMapping("toLoginPage")
    public ModelAndView toLoginPage(){//返回登录页面
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("login");
        return modelAndView;
    }
    @GetMapping("toMainPage")
    public ModelAndView toMainPage(){//返回首页
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("main");
        return modelAndView;
    }

    @PostMapping("login")
    public ModelAndView login(String username,String pwd,HttpSession session){
        //获取账号密码，检查是否正确，正确则跳转的首页，否则要求重输
        ModelAndView modelAndView = new ModelAndView();
        if("tom".equals(username)&&"123".equals(pwd)){
            //登录成功，在新的session中添加键值对，跳转到首页
            session.setAttribute("user",username);
            modelAndView.addObject("msg",username);
            modelAndView.setViewName("main");
        }else {//登录失败，跳转到登录页面
            modelAndView.addObject("msg","您输入的账号密码不正确，请重新输入！！");
            modelAndView.setViewName("login");
        }
        return modelAndView;
    }
    @GetMapping("download/{filename}")
    public ResponseEntity<byte[]> download(@PathVariable("filename") String filename, HttpServletRequest request)throws IOException{
        //到files文件夹下面去下载filename文件到浏览器,必须要手工生成返回消息数据包
        //获取存放文件夹的绝对路径
        String realPath = request.getServletContext().getRealPath("/WEB-INF/files/");
        File file = new File(realPath + filename);
        HttpHeaders httpHeaders=new HttpHeaders();
        httpHeaders.setContentDispositionFormData("attachment",filename);
        httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),httpHeaders, HttpStatus.OK);
    }

    @GetMapping("toDownloadPage")
    public ModelAndView toDownloadPage(HttpServletRequest request){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("fileList");
        List<String> filenames=new ArrayList<>();//存放含有绝对路径的文件名
        //到files文件夹里去读取，首先获取files的绝对路径
        String realPath = request.getServletContext().getRealPath("/WEB-INF/files/");
        File path = new File(realPath);
        if(!path.exists()) {
            modelAndView.addObject("msg","下载地文件夹不存在！！");
            return modelAndView;
        }
        File[] listFiles = path.listFiles();//返回该文件夹下面的所有文件
        if(listFiles.length==0){
            modelAndView.addObject("msg","该文件夹下没有可供下载地文件");
            return modelAndView;
        }
        for(File file:listFiles){
            filenames.add(file.getName());
        }
        modelAndView.addObject("files",filenames);
        return modelAndView;
    }

    @GetMapping("toPage/{page}")
    public String toPage(@PathVariable("page") String page){
           return page;
    }

    @PostMapping("fileUpLoad")
    public String fileUpLoad(Model model,@RequestParam("upload") List<MultipartFile> uploadFiles, HttpServletRequest request)throws IOException{
        //接收上传的文件，保存到服务器中WEB-INF/files文件夹中
        if (uploadFiles.size()==1){
            String originalFilename = uploadFiles.get(0).getOriginalFilename();
            if(originalFilename==null||originalFilename.isEmpty())
            {
                model.addAttribute("msg","上传失败，请重新上传");
                return "fileupload";
            }
        }
        for(MultipartFile file:uploadFiles){
            String originalFilename = file.getOriginalFilename();
            if(originalFilename==null||originalFilename.isEmpty())
                continue;
            String newFilename= UUID.randomUUID()+originalFilename;
            //获取存放文件夹的绝对路径
            String realPath = request.getServletContext().getRealPath("/WEB-INF/files/");
            //判断该文件夹是否存在，不存在就新建
            File saveDir = new File(realPath);//先创建文件夹对象，再使用文件夹对象的方法来判断是否存在这样的路径
            if(!saveDir.exists()) saveDir.mkdirs();
            File dest=new File(realPath+newFilename);
            file.transferTo(dest);//参数完整地文件名
        }
        return "redirect:toDownloadPage";
    }



    @PostMapping("registerJSON")
    public void registerJSON(@RequestBody User user){
        System.out.println(user);
    }

    @PostMapping("testJSON")
    @ResponseBody
    public User testJSON(@RequestBody List<User> users){
        System.out.println(users);
        return users.get(0);
    }


    @GetMapping("rest/{i}/{n}")
    public void rest(@PathVariable("i") Integer id,@PathVariable("n")String name){
        System.out.println(id);
        System.out.println(name);
    }

    @PostMapping("register")
    public void register(User user){
        System.out.println(user);
    }


    @GetMapping("simple")
    public ModelAndView simple(@RequestParam(value = "id",required = false,defaultValue ="3") Integer ids,@RequestParam(value = "name",required = false) String names){
        System.out.println(ids);
        System.out.println(names);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("simple");
        modelAndView.addObject("msg",names);
        return modelAndView;
    }


    @GetMapping("testDefault")
    public String testDefault(HttpServletRequest request){
        String id = request.getParameter("id");
        System.out.println(id);
        return "simple";
    }

    //在浏览器地址栏输入地址“/hello1，就执行这个方法,返回页面hello.jsp，同时替换这个页面中变量”
    @GetMapping("hello1")
    public ModelAndView hello1(){
        System.out.println("111111");
//        int a=1/0;
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("hello");//返回的页面名字，一般只需要写页面的文件名，地址和扩展名在spring配置文件中配置
        modelAndView.addObject("msg","111111");
        return modelAndView;
    }

    //在浏览器地址栏输入地址“/hello2，就执行这个方法”
    @GetMapping("hello2")
    public ModelAndView hello2(){
        System.out.println("222222");
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("hello");//返回的页面名字，一般只需要写页面的文件名，地址和扩展名在spring配置文件中配置
        modelAndView.addObject("msg","222222");
        return modelAndView;
    }

    //在浏览器地址栏输入地址“/hello3，就执行这个方法”
    @GetMapping("hello3")
    public ModelAndView hello3(){
        System.out.println("333333");
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("hello");//返回的页面名字，一般只需要写页面的文件名，地址和扩展名在spring配置文件中配置
        modelAndView.addObject("msg","3333333");
        return modelAndView;
    }

    @GetMapping("hello4")
    @ResponseBody
    //返回的对象不是页面，而是对象的json数据
    public String hello4(){
        System.out.println("44444");
        return "ok";
    }
}
